package com.eascs.ticket.configuration.service;

import java.util.Date;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.common.assertion.util.AssertInfoUtils;
import com.eascs.common.util.DateUtils;
import com.eascs.ticket.common.entity.EntityUtil;
import com.eascs.ticket.common.service.BaseSevice;
import com.eascs.ticket.configuration.entity.Workday;
import com.eascs.ticket.configuration.entity.WorkdayUpdate;
import com.eascs.ticket.configuration.entity.YesNoConstant;

@Service
public class WorkdayService extends BaseSevice {

	@Transactional(transactionManager = "ticketTransactionManager")
	public int buildDay(Date from, Date to) {
		AssertInfoUtils.assertTrue(to.getTime() - from.getTime() >= 0, "截止时间必需大于或者等于开始时间");
		Date day = from;
		int days = 0;
		while (to.getTime() - day.getTime() >= 0) {
			Workday workday = new Workday();
			workday.setDay(day);
			workday.setWork(YesNoConstant.YES);
			if (DateUtils.getWeekOfDate(day) == 1 || DateUtils.getWeekOfDate(day) == 7) {
				workday.setWork(YesNoConstant.NO);
			}
			EntityUtil.initInsertEntity(workday);
			this.proxyDao.insert(workday);
			day = DateUtils.addDate(day, 1);
			days++;
		}
		return days;
	}

	public PageResult<Object[]> getWorkdays(Integer pageIndex) {
		SqlPageQuery<Object[]> sqlPageQuery = new SqlPageQuery<>(Object[].class, 100, pageIndex);
		sqlPageQuery.setQuerySql("select id, date_format(day,'%y-%m-%d'),work from workday order by day ");
		return this.proxyDao.findDataWithPage(sqlPageQuery);
	}

	public Workday getWorkday(String workdayId) {
		return this.proxyDao.getById(Workday.class, workdayId);
	}

	@Transactional(transactionManager = "ticketTransactionManager")
	public WorkdayUpdate updateWork(WorkdayUpdate workdayUpdate) {
		this.proxyDao.updateById(workdayUpdate);
		return workdayUpdate;
	}

	public Date getNextWorkDay() {
		return this.getNextWorkDay(new Date());
	}

	public Date getNextWorkDay(Date day) {
		return this.getNextWorkDay(day, 0);
	}

	public Date getNextWorkDay(int days) {
		return this.getNextWorkDay(new Date(), days);
	}

	public Date getNextWorkDay(Date day, int days) {
		String sql = "select day from workday where work='Y' and day>=? order by day limit ?,1";
		return this.proxyDao.findSimpleObject(sql, Date.class, DateUtils.truncateTime(day), days);
	}

	public int calculateWorkDays(Date from, Date to) {
		return this.proxyDao.findInteger("select count(1) from workday where  work='Y' and day>=? and day<=? ", DateUtils.truncateTime(from), DateUtils.truncateTime(to));
	}

	public boolean isWorkDay(Date day) {
		return this.proxyDao.findInteger("select count(1) from workday where  work='Y' and day=? ", DateUtils.truncateTime(day)) > 0;
	}

}
